// pages/useroperation/useroperation.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        title: 'opinion',
        
        // 绑定学籍
        studentId: '',
        name: '',

        // 发布活动
        activityName: '',
        activityTime: '',
        activityTarget: '',
        activityContent: '',
        // 图(占位图)
        imgsrc1: 'http://175.178.67.243/icon/img_load.png',
        imgsrc2: 'http://175.178.67.243/icon/img_load.png',
        imgsrc3: 'http://175.178.67.243/icon/img_load.png',

        // 意见
        opinion: '',

        // 积分
        integralList: [],
        integral: 0
    },
    // 绑定学籍按钮点击
    infoClick() {
        if (this.data.studentId === '' || this.data.name === '') {
            wx.showToast({
                title: '数据不能为空',
                icon: 'error',
                duration: 2000
            })
            return
        }

        const that = this

        wx.request({
          url: getApp().globalData.backUrl + '/request/updateWxUser',
          method: 'POST',
          data: {
            userId: getApp().globalData.userInfo._id,
            studentId: this.data.studentId,
            name: this.data.name
          },
          success(res) {
            if (res.statusCode === 200 && res.data.code === 200) {
                getApp().globalData.userInfo.studentId = that.data.studentId
                getApp().globalData.userInfo.name = that.data.name
                wx.navigateTo({url: '/pages/info/info?type=success&info='+res.data.message,})
            }
          }
        })
    },
    // 加载本地图片
    loadImage(event) {
        const that = this
        wx.chooseImage({
            count: 1,
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            success: function (res) {
                that.setData({[event.target.dataset.type]: res.tempFilePaths[0]})
            }
        })
    },
    // 活动发布点击
    async activityClick() {
        
        if (this.data.activityName === '' || this.data.activityTime === '' || this.data.activityTarget === '' || this.data.activityContent === '') {
            wx.showToast({
                title: '数据不能为空',
                icon: 'error',
                duration: 2000
            })
            return
        }

        wx.showLoading({
          title: '发布中',
          mask: true
        })

        wx.request({
          url: getApp().globalData.backUrl + '/request/saveActivity',
          method: 'POST',
          data: {
            userId: getApp().globalData.userInfo._id,
            activityName: this.data.activityName,
            activityTime: this.data.activityTime,
            activityTarget: this.data.activityTarget,
            activityContent: this.data.activityContent,
            img1: await this.image_to_base64(this.data.imgsrc1),
            img2: await this.image_to_base64(this.data.imgsrc2),
            img3: await this.image_to_base64(this.data.imgsrc3),
          }, 
          success(res) {
              wx.hideLoading()
              if (res.statusCode === 200 && res.data.code === 200) {
                wx.navigateTo({url: '/pages/info/info?type=success&info='+res.data.message,})
              }else {
                  wx.showToast({
                    icon: "error",
                    title: '发布失败',
                  })
              }
          },
          fail(err) {
              console.log(err);
          }
        })
    },
    async image_to_base64(url){
        return new Promise((resolve,reject) => {
            wx.getFileSystemManager().readFile({
                filePath: url, //选择图片返回的相对路径
                encoding: 'base64', //编码格式
                success: res => { //成功的回调
                    resolve('data:image/png;base64,' + res.data)
                },
                fail(err) {
                    console.log(err);
                    reject(err)
                }
            })
        })
    },

    // 意见提交
    opinionClick() {
        const that = this
        wx.request({
          url: getApp().globalData.backUrl + '/request/saveOpinion',
          method: 'POST',
          data: {
            userId: getApp().globalData.userInfo._id,
            time: new Date().toISOString(),
            content: that.data.opinion
          },
          success(res) {
              if (res.statusCode === 200 && res.data.code === 200) {
                wx.navigateTo({url: '/pages/info/info?type=success&info=提交成功',})
              }else {
                  wx.showToast({
                    title: '提交意见失败',
                    icon: 'error'
                  })
              }
          }
        })
        
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        // 配置页面信息
        switch(options.title) {
            case 'info' : {
                wx.setNavigationBarTitle({title: '信息绑定'})
            } break;
            case 'integral' : {
                wx.setNavigationBarTitle({title: '积分详情'})
                wx.setNavigationBarColor({
                  backgroundColor: '#23B5FF',
                  frontColor: '#ffffff',
                })
            } break;
            case 'activity' : {
                wx.setNavigationBarTitle({title: '活动发布'})
            } break;
            case 'opinion' : {
                wx.setNavigationBarTitle({title: '意见反馈'})
            } break;
        }
        this.setData(options)

        const that = this
        // 各个页面初始化
        if (this.data.title === 'info') {
            // 引入学籍信息
            let s = getApp().globalData.userInfo.studentId || ''
            let n = getApp().globalData.userInfo.name || ''
            this.setData({studentId: s,name: n})
        }else if (this.data.title === 'integral') {
            wx.request({
              url: getApp().globalData.backUrl + '/request/getIntegral',
              success(res) {
                  if (res.statusCode === 200 && res.data.code === 200) {
                    for (const item of res.data.integralList) {
                        item.time = item.time.split('T')[0]
                    }
                    that.setData({integralList: res.data.integralList})
                  }else {
                      wx.showToast({
                        title: '请求积分列表失败',
                        icon: 'none'
                      })
                  }
              }
            })
            this.setData({integral: getApp().globalData.userInfo.integral})
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})